<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>第一步：搭架子</title>
        <script type="text/javascript" src="./threejs/three.js"></script>
        <script type="text/javascript" src="./threejs/controls/TrackballControls.js"></script>

        <link rel="stylesheet" href="./reset.import.css">
        <style type="text/css">
            div#canvas-frame {
                cursor: pointer;
                width:100%;
                height:100%;
                background-color: #EEEEEE;
            }
        </style>
    </head>
    <body onload="threeStart();">
        <div id="canvas-frame"></div>
        <script>
            var renderer;//渲染器
            var width;//页面宽度
            var height;//页面高度
            var origPoint = new THREE.Vector3(0, 0, 0);//原点
            var controls;
            
            window.requestAnimFrame = (function() {//如果有变化则可能还需要requestAnimationFrame刷新
                return window.requestAnimationFrame ||
                       window.mozRequestAnimationFrame ||
                       window.webkitRequestAnimationFrame ||
                       window.msRequestAnimationFrame ||
                       window.webkitRequestAnimationFrame;
            })();

            //开始
            function threeStart() {
                initThree();
                initCamera();
                initScene();
                initLight();
                initObject();
                render();

                window.addEventListener( 'resize', onWindowResize, false );
                
                animate();
            }

            //根据页面宽度和高度创建渲染器，并添加容器中
            function initThree() {
                width = window.innerWidth;
                height = window.innerHeight;
                renderer = new THREE.WebGLRenderer({
                    antialias : true //抗锯齿开启
                });

                renderer.setSize(width, height); //设置渲染器宽度和高度
                renderer.setClearColor(0xFFFFFF, 1.0); //设置背景颜色
                renderer.setPixelRatio(window.devicePixelRatio);//设置设备像素比
                document.getElementById('canvas-frame').appendChild(renderer.domElement);//把渲染器放置到页面中
            }

            //创建相机，并设置正方向和中心点
            var camera;
            function initCamera() {
                camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
				camera.position.z = 500;
				controls = new THREE.TrackballControls( camera );
				controls.rotateSpeed = 2;
				controls.zoomSpeed = 1.2;
				controls.panSpeed = 0.8;
				controls.noZoom = false;
				controls.noPan = false;
				controls.staticMoving = true;
				controls.dynamicDampingFactor = 0.3;
				controls.keys = [ 65, 83, 68 ];

				controls.addEventListener( 'change', render );           
            }

            //创建场景，后续元素需要加入到场景中才会显示出来
            var scene;
            function initScene() {
                scene = new THREE.Scene();
            }

            //创建光线
            var light;
            function initLight() {
                //点光源
                /*
					pointLight = new THREE.PointLight( 0xffffff, 1, 2000 );
					pointLight.position.set(70, 112, 98);
					scene.add(pointLight);
				*/

                //环境光
                ambientLight = new THREE.AmbientLight( 0xfefefe );
                scene.add(ambientLight);
            }

            //创建展示场景所需的各种元素
            var cubes;

            function initObject() {
				var group = new THREE.Group();

                //坐标轴
                var xmat = new THREE.LineBasicMaterial({ color: 0xff0000 });
                var xgeo = new THREE.Geometry();
                xgeo.vertices.push(
                        new THREE.Vector3(0, 0, 0),
                        new THREE.Vector3(300, 0, 0)
                );

                var xline = new THREE.Line(xgeo, xmat);
                
                group.add(xline);

                var ymat = new THREE.LineBasicMaterial({ color: 0x00ff00 });
                var ygeo = new THREE.Geometry();
                ygeo.vertices.push(
                        new THREE.Vector3(0, 0, 0),
                        new THREE.Vector3(0, 300, 0)
                );
                var yline = new THREE.Line(ygeo, ymat);
                group.add(yline);

                var zmat = new THREE.LineBasicMaterial({ color: 0x0000ff });
                var zgeo = new THREE.Geometry();
                zgeo.vertices.push(
                        new THREE.Vector3(0, 0, 0),
                        new THREE.Vector3(0, 0, 300)
                );
                var zline = new THREE.Line(zgeo, zmat);
                group.add(zline);

                // var geometry = new THREE.BoxGeometry( 100, 100, 100);
                // var material = new THREE.MeshLambertMaterial( {color: 0xff0000} );
                // cube = new THREE.Mesh( geometry, material );
                // cube.position.set(0,0,0);
                // scene.add(cube);

                cubes = SimpleCube(0,0,0,3,50,['#ff6b02', '#dd422f',
                            '#ffffff', '#fdcd02',
                            '#3d81f7', '#019d53']);
                
                cubes.forEach(cube=>{
                    group.add(cube);
                })

				group.rotateY(45 / 180 * Math.PI);

				scene.add(group);
            }

            function SimpleCube(x, y, z, num, len, colors) {
            //魔方左上角坐标
            var leftUpX = x - num/2*len;
            var leftUpY = y + num/2*len;
            var leftUpZ = z + num/2*len;

            var cubes = [];
            for (var i = 0; i < num; i++) {
                for (var j = 0; j < num * num; j++) {

                    var myFaces = [];
                    for (var k = 0; k < 6; k++) {
                        myFaces[k] = faces(colors[k]);
                    }

                    var materials = [];
                    for (var k = 0; k < 6; k++) {
                        var texture = new THREE.Texture(myFaces[k]);
                        texture.needsUpdate = true;
                        materials.push(new THREE.MeshLambertMaterial({ map: texture}));
                    }

                    var cubegeo = new THREE.BoxGeometry(len, len, len);
                    var cube = new THREE.Mesh(cubegeo, materials);

                    //依次计算各个小方块中心点坐标
                    cube.position.x = (leftUpX + len / 2) + (j % num) * len;
                    cube.position.y = (leftUpY - len / 2) - parseInt(j / num) * len;
                    cube.position.z = (leftUpZ - len / 2) - i * len;
                    cubes.push(cube)
                }
            }
            return cubes;
        }

        function faces(rgbaColor) {
            var canvas = document.createElement('canvas');
            canvas.width = 256;
            canvas.height = 256;
            var context = canvas.getContext('2d');
            //画一个宽高都是256的黑色正方形
            context.fillStyle = 'rgba(0,0,0,1)';
            context.fillRect(0, 0, 256, 256);
            //在内部用某颜色的16px宽的线再画一个宽高为224的圆角正方形并用改颜色填充
            context.rect(16, 16, 224, 224);
            context.lineJoin = 'round';
            context.lineWidth = 16;
            context.fillStyle = rgbaColor;
            context.strokeStyle = rgbaColor;
            context.stroke();
            context.fill();
            return canvas;
        }

        function animate() {
            requestAnimationFrame( animate );
            
            controls.update();
        }

        function render() {
            renderer.render( scene, camera );
        }
        
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
            controls.handleResize();
            render();
        }
        </script>
    </body>
</html>